/*===========================================
    GRRLIB (GX Version)
============================================*/
#include <grrlib.h>

#include <stdlib.h>
#include <wiiuse/wpad.h>
#include <fat.h>
#include <dirent.h>
#include <unistd.h>
#include "global.h"
#include "console.h"
#include "Download.h"

#include "font_png.h"

#include "game.h"

using namespace std;


// -- Prototypes -------------------------
bool UpdateGame();
void Debug(const char *msg);
void Progress();
static void *progressinitcallback(void *arg);

// -- Global variables -------------------
static lwp_t progressthread = LWP_THREAD_NULL;
bool resume_thread = true;
GRRLIB_texImg *texFont;


int main() {
    // Initialise the Graphics & Video subsystem
    GRRLIB_Init();
    // Initialise the Wiimotes
    WPAD_Init();
	// Initialise SD
	fatInitDefault();
	
	GRRLIB_Settings.antialias = true;
	
	GRRLIB_SetBlend(GRRLIB_BLEND_ALPHA);
	
	//Splashscreen();
	
	// White bg
	GRRLIB_SetBackgroundColour(255, 255, 255, 255);
	
	// Font
	texFont = GRRLIB_LoadTexture(font_png);
	GRRLIB_InitTileSet(texFont, 8, 16, 0);
	
	Game *game = new Game(texFont);
	
	Console &console = Console::GetConsole();
	
	bool run = true;
	
	mkdir("/apps/", 0777);
	mkdir("/apps/platform/", 0777);

	console.Print("Game successfully initalized!");

    while(run) {
		// Menu loop
		while(1) {
			WPAD_ScanPads();
			
			if(WPAD_ButtonsDown(0) & WPAD_BUTTON_HOME) {
				run = false;
				break;
			}
			if(WPAD_ButtonsDown(0) & WPAD_BUTTON_A) break;
			if(WPAD_ButtonsDown(0) & WPAD_BUTTON_MINUS) {
				UpdateGame();
			}
		
			game->Menu();
			
			// Show console?
			if(game->ConsoleEnabled()) {
				console.Render();
			}
			
			// Render the frame buffer to the TV
			GRRLIB_Render();
		}
		
		// Game loop
		while(run) {
			// Scan the Wiimotes
			WPAD_ScanPads();
			if (WPAD_ButtonsDown(0) & WPAD_BUTTON_HOME)  break;
			
			game->Play();
			
			if(game->ConsoleEnabled()) {
				console.Render();
			}
			
			// Render the frame buffer to the TV
			GRRLIB_Render();
		}
    }
	
	// Free memory
	GRRLIB_FreeTexture(texFont);
	delete game;
	console.Delete();

    GRRLIB_Exit(); // Be a good boy, clear the memory allocated by GRRLIB

    exit(0);  // Use exit() to exit a program, do not use 'return' from main()
	
	return 0;
}


bool UpdateGame() {
	LWP_CreateThread(&progressthread, progressinitcallback, NULL, NULL, 0, 0);
	Download dl; 
	bool ret = dl.Update();
	
	resume_thread = false;
	
	return ret;
}

void Debug(const char *msg) {
	while(1) {
		WPAD_ScanPads();
		if(WPAD_ButtonsDown(0) & WPAD_BUTTON_A) break;
		
		GRRLIB_Printf(6, 12, texFont, GRRLIB_BLACK, 1, "%s     [+] A to continue...", msg);
		GRRLIB_Render();
	}
}

void Progress() {
	Console &console = Console::GetConsole();
	
	while(resume_thread) {
		WPAD_ScanPads();
		
		console.Render();
		GRRLIB_Render();
		
		if(WPAD_ButtonsDown(0) & WPAD_BUTTON_HOME) break;
	}
	resume_thread = true;
}

static void *progressinitcallback(void *arg) { 
	Progress();
	
	return 0;
}
